import {Footer} from '@/components';
import {Button, Col, Drawer, Image, Row, Space, Tooltip} from 'antd';
import {
  LockOutlined,
  MobileOutlined, QuestionCircleOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {FormattedMessage, history, SelectLang, useIntl, useModel, Helmet} from '@umijs/max';
import {message, Tabs} from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, {useState} from 'react';
import {createStyles} from 'antd-style';
import {baseLoginUsingPost, loginByEmailUsingPost} from "@/services/xs-Ai-user/userController";
import {sendEmailCodeUsingGet} from "@/services/xs-Ai-user/verifyController";
import "./index.less"
import ScanLogin from "@/pages/User/Login/component/ScanLogin";

const useStyles = createStyles(({token}) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});
const Lang = () => {
  const {styles} = useStyles();

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang/>}
    </div>
  );
};


const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const {initialState, setInitialState} = useModel('@@initialState');
  const {styles} = useStyles();
  const intl = useIntl();
  const [random, setRandom] = useState<number>();
  const [open, setOpen] = useState(false);



  const handleSubmit = async (values: API.AccountLoginRequest) => {
    try {
      // 登录
      const msg = await baseLoginUsingPost({...values});
      if (msg.data) {
        const defaultLoginSuccessMessage = '登录成功';
        message.success(defaultLoginSuccessMessage);
        const urlParams = new URL(window.location.href).searchParams;
        await setInitialState({
          loginUser: msg.data
        })
        setTimeout(() => {
          history.push(urlParams.get('redirect') || '/')
          window.location.reload(); // 刷新页面，解决可能出现的元素渲染问题

        }, 100)
        return;
      }
      message.error('登录失败-' + msg.message);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！'
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
    setRandom(Math.random())
  };
  const onClose = () => {
    setOpen(false);
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang/>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg"/>}
          title="Ant Design"
          subTitle={intl.formatMessage({id: 'pages.layouts.userLayout.title'})}
          initialValues={{
            autoLogin: true,
          }}
          actions={[
            <div key={'another-login'} style={{display: 'flex', justifyContent: 'space-around', alignItems: 'center'}}>
              <div key={'desc'}>
                其他登录方式：
              </div>
              <Tooltip placement="bottom" title='钉钉扫码登陆，仅限内部成员使用' color={'#5c76e0'}>
                <div key={random} className={'dingding-icon'} style={{marginLeft: '-180px'}} onClick={() => {
                    setOpen(true)
                }}>
                  <svg t="1720530444758" className="icon" viewBox="0 0 1024 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="1448" width="30" height="30">
                    <path
                      d="M1002.666667 83.2c-14.933333-27.733333-36.266667-46.933333-61.866667-61.866667-27.733333-14.933333-53.333333-21.333333-125.866667-21.333333H211.2c-72.533333 0-100.266667 8.533333-128 21.333333-25.6 14.933333-46.933333 36.266667-61.866667 61.866667-12.8 27.733333-21.333333 55.466667-21.333333 128v601.6c0 72.533333 8.533333 100.266667 21.333333 125.866667 14.933333 27.733333 36.266667 46.933333 61.866667 61.866666 27.733333 14.933333 53.333333 21.333333 125.866667 21.333334H810.666667c72.533333 0 100.266667-8.533333 125.866666-21.333334 27.733333-14.933333 46.933333-36.266667 61.866667-61.866666 14.933333-27.733333 21.333333-53.333333 21.333333-125.866667V211.2c4.266667-72.533333-4.266667-100.266667-17.066666-128zM765.866667 437.333333c-2.133333 4.266667-4.266667 12.8-8.533334 21.333334-23.466667 49.066667-81.066667 145.066667-81.066666 145.066666l-17.066667 29.866667h83.2l-160 215.466667L618.666667 704h-66.133334l23.466667-96c-21.333333 6.4-44.8 12.8-66.133333 19.2 0 0-34.133333 21.333333-100.266667-40.533333 0 0-44.8-40.533333-19.2-49.066667 10.666667-4.266667 53.333333-8.533333 87.466667-14.933333 44.8-6.4 72.533333-8.533333 72.533333-8.533334s-138.666667 2.133333-170.666667-2.133333-74.666667-59.733333-83.2-108.8c0 0-12.8-27.733333 29.866667-14.933333 42.666667 12.8 221.866667 49.066667 221.866667 49.066666S313.6 362.666667 298.666667 345.6c-14.933333-17.066667-44.8-96-42.666667-145.066667 0 0 2.133333-12.8 14.933333-8.533333 0 0 172.8 78.933333 290.133334 123.733333 117.333333 42.666667 219.733333 66.133333 204.8 121.6z"
                      fill="#3296FA" p-id="1449"></path>
                  </svg>
                </div>
              </Tooltip>

            </div>
          ]}
          onFinish={async (values) => {
            if (type === 'account') {
              await handleSubmit(values as API.AccountLoginRequest);
            } else if (type === 'email') {
              console.log('邮箱登录，登录参数:' + JSON.stringify(values))
              const emailLoginRes = await loginByEmailUsingPost(values as API.EmailLoginRequest)
              if (emailLoginRes.data) {
                message.success('登录成功');
                const urlParams = new URL(window.location.href).searchParams;
                await setInitialState({
                  loginUser: emailLoginRes.data
                })
                setTimeout(() => {
                  history.push(urlParams.get('redirect') || '/')
                  window.location.reload(); // 刷新页面，解决可能出现的元素渲染问题
                }, 100)
                return;
              }
              message.error('登录失败-' + emailLoginRes.message);
            }
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'account',
                label: intl.formatMessage({
                  id: 'pages.login.accountLogin.tab',
                  defaultMessage: '账户密码登录',
                }),
              },
              {
                key: 'email',
                label: intl.formatMessage({
                  id: 'pages.login.phoneLogin.tab2',
                  defaultMessage: '邮箱登录',
                }),
              },
            ]}
          />

          {type === 'account' && (
            <>
              <ProFormText
                initialValue={'白小帅'}
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder1',
                  defaultMessage: '用户名: 白小帅',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                initialValue={'88888888'}
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder2',
                  defaultMessage: '密码: 88888888',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
              <Row>
                <Col span={12}>
                  <Space size={12} align="center">
                    <ProFormText
                      name="captcha"
                      fieldProps={{
                        size: 'large',
                        prefix: <QuestionCircleOutlined/>,
                      }}

                      placeholder={intl.formatMessage({
                        id: 'pages.login.username.placeholder-code',
                        defaultMessage: '验证码',
                      })}
                      rules={[
                        {
                          required: true,
                          message: (
                            <FormattedMessage
                              id="pages.login.username.required"
                              defaultMessage="请输入用户名!"
                            />
                          ),
                        },
                      ]}
                    />
                  </Space>
                </Col>
                <Col span={12}>
                  <Space size={12} align="center">
                    <Image
                      width={80}
                      height={39}
                      style={{
                        borderRadius: '8px',
                        marginLeft: '10px',
                      }}
                      src={`http://localhost:8080/user/verify/captcha?${random}`}
                      // placeholder={
                      //   <Image
                      //     width={80}
                      //     height={39}
                      //     preview={false}
                      //     src="http://localhost:8080/user/verify/captcha"
                      //   />
                      // }
                    />
                    <Button
                      style={{
                        width: 50,
                        height: 40,
                        marginLeft: '10px',
                      }}
                      type="primary"
                      ghost
                      onClick={() => {
                        setRandom(Date.now());
                      }}
                    >
                      换一张
                    </Button>
                  </Space>
                </Col>
              </Row>
            </>
          )}

          {type === 'email' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined/>,
                }}
                name="email"
                placeholder={'请输入邮箱账号'}
                rules={[
                  {
                    required: true,
                    message: '邮箱号是必填项！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入邮箱验证码'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="code"
                phoneName="email"
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={async (values) => {
                  const result = await sendEmailCodeUsingGet({
                    email: values
                  });
                  if (result.data) {
                    message.success('验证码发送成功！');
                    return;
                  }
                  message.error('验证码发送失败！');
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录"/>
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码"/>
            </a>
          </div>
        </LoginForm>
      </div>
      <Drawer title="钉钉扫码登录" placement="right" onClose={onClose} open={open}>
        <ScanLogin />
      </Drawer>
      <Footer/>
    </div>
  );
};

export default Login;
